//
//  ViewController.swift
//  swift二维码扫描
//
//  Created by cvicseks-mac1 on 16/3/9.
//  Copyright © 2016年 cvicseks-mac1. All rights reserved.
//

import UIKit
import Foundation
import AVFoundation
class ViewController: UIViewController , AVCaptureMetadataOutputObjectsDelegate ,UIAlertViewDelegate{
    // AVCaptureDevice这里代表抽象的硬件设备
    let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
    // AVCaptureSession它是input和output的桥梁它协调着intput到output的数据传输。
    let session = AVCaptureSession()
    //Swift语言使用var定义变量，但和别的语言不同，Swift里不会自动给变量赋初始值，也就是说变量不会有默认值，所以要求使用变量之前必须要对其初始化。如果在使用变量之前不进行初始化就会报错,Optional其实是个enum，里面有None和Some两种类型。其实所谓的nil就是Optional.None, 非nil就是Optional.Some, 然后会通过Some(T)包装（wrap）原始值，这也是为什么在使用Optional的时候要拆包（从enum里取出来原始值）的原因, 也是PlayGround会把Optional值显示为类似{Some "hello world"}的原因，这里是enum Optional的定义 声明为Optional只需要在类型后面紧跟一个?即可
    //一旦声明为Optional的，如果不显式的赋值就会有个默认值nil。判断一个Optional的值是否有值，可以用if来判断
    //1.声明Optional值变量
    //2.用在对Optional值操作中，用来判断是否能响应后面的操作
    var layer : AVCaptureVideoPreviewLayer?
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.setupCamera()
        self.session.startRunning()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "二维码扫描"
        view.backgroundColor = UIColor.whiteColor()
//        let imageView: UIImageView = UIImageView(frame:CGRectMake( UIScreen.mainScreen().bounds.size.width/2-300, 140, 300, 300))
        let imageView: UIImageView = UIImageView(frame:CGRectMake( 10, 140, 300, 300))
        imageView.image = UIImage(named: "pick_bg")
        imageView.layer.borderWidth = 1
        imageView.layer.borderColor = UIColor.redColor().CGColor
        view.addSubview(imageView)
        
    }
    
    func setupCamera(){
        self.session.sessionPreset = AVCaptureSessionPresetHigh
        var error: NSError?
        //   AVCaptureInput。这里代表输入设备（可以是它的子类），它配置抽象硬件设备的ports。
        let input: AVCaptureDeviceInput!
        do{
            input = try AVCaptureDeviceInput(device: device)
        }catch let error1 as NSError{
            error = error1
            input = nil
        }
        if(error != nil){
            print(error?.description)
            return
        }
        if session.canAddInput(input){
            session.addInput(input)
        }
        layer = AVCaptureVideoPreviewLayer(session: session)
        layer!.videoGravity = AVLayerVideoGravityResizeAspectFill
        layer!.frame = CGRectMake(20,150,280,280);
        self.view.layer.insertSublayer(layer!, atIndex: 0)
        
        //AVCaptureOutput。它代表输出数据，管理着输出到一个movie或者图像。
        let output = AVCaptureMetadataOutput()
        output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
        if session.canAddOutput(output) {
            session.addOutput(output)
            output.metadataObjectTypes = [AVMetadataObjectTypeQRCode];
        }
        
        session.startRunning()
    }
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
        var stringValue:String?
        if metadataObjects.count > 0 {
            let metadataObject = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
            stringValue = metadataObject.stringValue
        }
        self.session.stopRunning()
        print("code is \(stringValue)")
        
        //        let alertController = UIAlertController(title: "二维码", message: "扫到的二维码内容为:\(stringValue)", preferredStyle: UIAlertControllerStyle.Alert)
        //        alertController.addAction(UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: nil))
        //        self.presentViewController(alertController, animated: true, completion: nil)
        let alertView = UIAlertView()
        alertView.delegate=self
        alertView.title = "二维码"
        alertView.message = "扫到的二维码内容为:\(stringValue)"
        alertView.addButtonWithTitle("确认")
        alertView.show()
    }
    
    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
        session.startRunning()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

